package com.yxinsur.imc.business.client;


import com.aliyun.openservices.ons.api.MessageListener;
import com.aliyun.openservices.ons.api.PropertyKeyConst;
import com.aliyun.openservices.ons.api.bean.ConsumerBean;
import com.aliyun.openservices.ons.api.bean.Subscription;
import com.yxinsur.imc.business.listener.BusinessMqMessageListener;
import com.yxinsur.imc.common.rocketMq.config.MqConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 注入配置、订阅消息、添加消息处理的方法
 */
@Configuration
public class ConsumerClient {
    @Autowired
    private MqConfig mqConfig;

    //普通消息监听器，Consumer注册消息监听器来订阅消息.
    @Autowired
    private BusinessMqMessageListener messageListener;

    @Bean(initMethod = "start", destroyMethod = "shutdown")
    public ConsumerBean buildConsumer() {
        ConsumerBean consumerBean = new ConsumerBean();
        //配置文件
        Properties properties = mqConfig.getMqPropertie();
        //消息重试次数最大值
        properties.put(PropertyKeyConst.MaxReconsumeTimes,"20");
        properties.setProperty(PropertyKeyConst.GROUP_ID, mqConfig.getGroupId());
        //将消费者线程数固定为20个 20为默认值
        properties.setProperty(PropertyKeyConst.ConsumeThreadNums, "20");
        consumerBean.setProperties(properties);
        //订阅消息
        Map<Subscription, MessageListener> subscriptionTable = new HashMap<Subscription, MessageListener>();
        //订阅消息
        Subscription subscriptionChannel = new Subscription();
        subscriptionChannel.setTopic(mqConfig.getTopic());
        subscriptionChannel.setExpression(mqConfig.getChannelTag());
        subscriptionTable.put(subscriptionChannel, messageListener);

        consumerBean.setSubscriptionTable(subscriptionTable);
        return consumerBean;
    }

}
